package com.ws.service;

import com.ws.domain.Cart;
import com.ws.mapper.CartsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CartsService {
    @Autowired
    private CartsDao cartsDao;
    @Autowired
    private GoodsService goodsService;
    /**
     * 根据用户id查询购物车的购物数量
     * @param userId
     * @return
     */
    public int getCount(int userId) {
        return cartsDao.selectSumAmountByUserId(userId);
    }

    public List<Cart> getList(int userId) {
        return pack(cartsDao.selectListByUserId(userId));
    }

    /**
     *   计算总价格
     * @param userId
     * @return
     */
    public long getTotal(int userId) {
        int total = 0;
        List<Cart> cartList = this.getList(userId);
        if(Objects.nonNull(cartList) && ! cartList.isEmpty()) {
            for(Cart cart : cartList) {
                total += cart.getGoods().getPrice() * cart.getAmount();
            }
        }
        //返回的是所有商品的总价格
        return total;
    }



    /**
     * 封装
     * 重载pack方法 将每一个cart对象进行pack
     * @param list
     * @return
     */
    private List<Cart> pack(List<Cart> list) {
        for(Cart cart : list) {
            cart = pack(cart);
        }
        return list;
    }

    private Cart pack(Cart cart) {
        if(Objects.nonNull(cart)) {
            //根据good_id将goods给cart
            cart.setGoods(goodsService.getById(cart.getGood_id()));
            //计算一个商品的总价格
            cart.setTotal(cart.getAmount() * cart.getGoods().getPrice());
        }
        //返回
        return cart;
    }
}
